import dTalkApi from '../core/dTalkApi';
import visitMonthPlanModel from '../model/visitMonthPlanModel';
import reportFormService from './reportFormService';
import storeRecoderModel from '../model/storeRecoderModel';
import consumerRecoderModel from '../model/consumerRecoderModel';
import * as moment from 'moment';
import dTalkApiUtil from 'dingtalk-app/dtalk/dTalkApiUtil';
import storeInfoModel from '../model/storeInfoModel';
import formDataService from './formDataService';

class VisitMonthPlanService {
    constructor() { }

    async getUserIdByCode(code: string, cache: any,access_token:string) {
        if (cache[code]) {
            return cache[code]
        } else {
            let result = await dTalkApi.getDingDingAdressList(code,access_token);
            // console.log(result.total);
            if (!result.list || result.list.length == 0) {
                console.log("工号", code, "未找到");
                return null;
            }
            cache[code] = result.list[0];
            return cache[code]
        }
    }

    async getUserOriginizationById(id:string,cache:any,access_token:string){
       let idList:any=[];
        if(cache[id]){
            return [];
        }else{
            let groupName:any=[];
            let province: any = '';
            let area: any = '';
            let model: any = '';
            let team: any = '';
            let nation: any = '';
            let provinceName: any = '';
            let areaName: any = '';
            let manageModelName: any = '';
            let teamName: any = '';
            let nationName: any = '';
            let info=await dTalkApi.getUserDetail(id,access_token);
           
            if (!info.roles) {
                console.log("---------------未分配角色-------------------------", info);
                return [];
            }
            let roles=info.roles;
            roles.map(it => {
                groupName.push(it.groupName);
            })
            //查询指定用户的所有上级父部门路径
            let json_Two = await dTalkApi.list_parent_depts(id,access_token);
            let deptParentList = json_Two.department;
            for (let index = 0; index < json_Two.department.length; index++) {
                let deptParentList = json_Two.department[index];
                if (groupName[0]=='销售') {
                    if(deptParentList.length==3){//B2B
                        province = '';
                        area ='';
                        model = deptParentList[0];
                        nation = deptParentList[1];
                    }else if(deptParentList.length==4) {
                        province = '';
                        area = deptParentList[0];
                        model = deptParentList[1];
                        nation = deptParentList[2];
                    }else if (deptParentList.length==5) {//改动过
                        province = deptParentList[0];
                        area = deptParentList[1];
                        model = deptParentList[2];
                        nation = deptParentList[3];
                    }
                }else if (groupName.includes('省份') ){//---------------------有问题
                   if (deptParentList.length==5) {
                        province = deptParentList[0];
                        area = deptParentList[1];
                        model = deptParentList[2];
                        nation = deptParentList[3];
                    }
                }else  if (groupName.includes('区域')) {//改动过
                    if(deptParentList.length==4){//B2B
                        province = '';
                        area = deptParentList[0];
                        model = deptParentList[1];
                        nation = deptParentList[2];
                    }
                }else   if (groupName.includes('模块')) {
                    if(deptParentList.length==3){//B2B
                        province = '';
                        area ='';
                        model =  deptParentList[0];
                        nation = deptParentList[1];
                    }
                }else if (groupName.includes('全国')) {
                    if(deptParentList.length==2){
                        province = '';
                        area = '';
                        model = '';
                        nation = deptParentList[0];
                    }
                } 
                if (province) {
                    let data1 = await dTalkApi.getDeptDetail(province,access_token);
                    if(data1){
                        provinceName = data1.name;//省份名称
                    }
                }
                if (area) {
                    let data2 = await dTalkApi.getDeptDetail(area,access_token);
                    if(data2){
                        areaName = data2.name;//区域名称
                    }
                }
                if (model) {
                    let data3 = await dTalkApi.getDeptDetail(model,access_token);
                    if(data3){
                        manageModelName = data3.name;//模块名称
                    }       
                }
                if (team) {
                    let data4 = await dTalkApi.getDeptDetail(team,access_token);
                    if(data4){
                        teamName = data4.name;//团队名称
                    }
                }
                if (nation) {
                    let data5 = await dTalkApi.getDeptDetail(nation,access_token);
                    if(data5){
                        nationName = data5.name;//全国名称
                    }
                }
            }
            // console.log('provinceName---------->',provinceName, 'areaName--------->',areaName, 
            // 'manageModelName---------->',manageModelName, ' teamName---------->',teamName, 
            // 'nationName------------->', nationName,'=================员工id:',id,'============')            
            return [provinceName,areaName,manageModelName,teamName,nationName,province,area,model,team,nation]
        }
      
    }

    //保存导入的计划数据
    async saveLeadeData(data: any[]) {
        console.log('保存导入的计划数据开始!!!!!!!!!!!!!!!!!!')
        console.log(data,'data_data_data_data_data_data_')
        let cache: any = {}
        let userIdList:any=[];
        let access_token=await dTalkApiUtil.getAccessToken();
        for (let index = 0; index < data.length; index++) {
            let item = data[index];
            for (let itemindex = 0; itemindex < item.length; itemindex++) {
                let element = item[itemindex];
                //element.employeeName   员工工号
                let provinceName: any = '';
                let areaName: any = '';
                let manageModelName: any = '';
                let teamName: any = '';
                let nationName: any = '';
                let province: any = '';
                let area: any = '';
                let model: any = '';
                let team: any = '';
                let nation: any = '';     
                
                let planDate2 = moment(element.planDate2).format('YYYY-MM-DD');
                let month = moment(element.planDate2).format('MM');
                if (!(element.employeeName==undefined)) {
                    let result = await this.getUserIdByCode(element.employeeName, cache,access_token)
                    if (!result) {
                        continue;
                    }
                    // console.log("---------------------------------", result, result.staffId);
                    let userId = result.staffId;
                    if(!userIdList.includes(userId)){
                        if(!(element.code == undefined )&& !(element.consumerName == undefined)){
                            userIdList.push(userId);
                        }
                        let s=await this.getUserOriginizationById(userId,cache,access_token);
                        if(s.length==0){
                          continue;
                        }
                        provinceName= s[0];
                        areaName = s[1];
                        manageModelName = s[2];
                        teamName= s[3];
                        nationName = s[4];
                        province =  s[5];
                        area=  s[6];
                        model =  s[7];
                        team =  s[8];
                        nation =  s[9];
                    }
                    let employeeInfo = await dTalkApi.getUserDetail(userId,access_token);
                    if (!employeeInfo&&!employeeInfo.roles) {
                        console.log("---------------未分配角色-------------------------", employeeInfo);
                        continue;
                    }
                   
                   
                    let department = employeeInfo.department;
                    let userName = employeeInfo.name;
                   
                    if (!(element.code == undefined )&& !(element.consumerName == undefined)) {
                        let type: any = '';
                        if (element.consumerName == '开会') {
                            type = '开会';
                            let a3 = await visitMonthPlanModel.create({
                                sourceId: userId + '&' + element.code,
                                userId: userId,
                                user: userName,
                                avatar: employeeInfo.avatar,
                                jobnumber: element.employeeName,
                                deptId: department,
                                provinceManager: '',
                                areaManager: '',
                                modelManager: "",      //模块负责人
                                nationalManager: "",//全国负责人
                                city: employeeInfo.workPlace,
                                roles: employeeInfo.roles,     //角色
                                province: province,//员工所在省份
                                area: area,//员工所在区域
                                manageModel: model,     //员工所在模块
                                team: team,//员工所在团队
                                nation: nation,
                                provinceName: provinceName,//省份名称
                                areaName: areaName,//区域名称
                                manageModelName: manageModelName,//模块名称
                                teamName: teamName,//团队名称
                                nationName: nationName,//全国名称
                                month: month,
                                visitRecoder: '',
                                channel: '',
                                mark: '',
                                planDate: planDate2,
                                consumerName: element.consumerName,
                                consumerCode: '',
                                rest: '',
                                meeting: '',
                                plantype: type,
                                planStatus: '申请取消',
                                customerType: '',
                                purpose: '',
                                comment: 1,
                                cancelApply: '否',
                                remark: '',
                                leadIndate: moment().format('YYYY-MM-DD')
                            });
                            //    console.log(a3,'a3_a3_a3_a3_a3_a3_a3_a3_a3_a3_a3_')  
                        } else if (element.consumerName == '休假') {
                            type = '休假';
                            let a4 = await visitMonthPlanModel.create( {
                                sourceId: userId + '&' + element.code,
                                userId: userId,
                                user: userName,
                                avatar: employeeInfo.avatar,
                                jobnumber: element.employeeName,
                                deptId: department,
                                provinceManager: '',
                                areaManager: '',
                                modelManager: "",      //模块负责人
                                nationalManager: "",//全国负责人
                                city: employeeInfo.workPlace,
                                roles: employeeInfo.roles,     //角色
                                province: province,//员工所在省份
                                area: area,//员工所在区域
                                manageModel: model,     //员工所在模块
                                team: team,//员工所在团队
                                nation: nation,
                                provinceName: provinceName,//省份名称
                                areaName: areaName,//区域名称
                                manageModelName: manageModelName,//模块名称
                                teamName: teamName,//团队名称
                                nationName: nationName,//全国名称
                                month: month,
                                visitRecoder: '',
                                channel: '',
                                mark: '',
                                planDate: planDate2,
                                consumerName: element.consumerName,
                                consumerCode: '',
                                rest: '',
                                meeting: '',
                                plantype: type,
                                planStatus: '申请取消',
                                customerType: '',
                                purpose: '',
                                comment: 1,
                                cancelApply: '否',
                                remark: '',
                                leadIndate: moment().format('YYYY-MM-DD')
                            });
                            //    console.log(a4,'a4_a4_a4_a4_a4_a4_a4_a4_a4_a4_')  
                        } else {
                            let code1: any = '';
                            if (element.code == undefined) {
                                code1 = '';
                            } else {
                                code1 = element.code;
                            }
                            let customerType:any='';
                            let data1 = await consumerRecoderModel.find({ consumerCode: code1, comment: 1 }, {});
                            let data2 = await storeInfoModel.find({ storeCode: code1 });
                            if (data1.length != 0) {
                                type = '现有客户';
                                customerType=data1[0].typeOne;
                            } else if (data2.length != 0) {
                                type = '门店';
                                customerType=data2[0].store_classification;
                            } else {
                                type = '新拓展客户';
                                customerType='';
                            }
                            let data = await visitMonthPlanModel.findOne({ planDate: element.planDate2, consumerCode: element.code, consumerName: element.consumerName, jobnumber: element.employeeName });
                            
                          
                            if (data) {
                                console.log("执行修改", data._id )
                                let a_1 = await visitMonthPlanModel.update({ _id: data._id }, {
                                    sourceId: userId + '&' + element.code,
                                    userId: userId,
                                    user: userName,
                                    avatar: employeeInfo.avatar,
                                    jobnumber: element.employeeName,
                                    consumerCode: element.code,
                                    consumerName: element.consumerName,
                                    customerType:customerType,
                                    plantype: type,
                                    planDate: planDate2,
                                    planStatus: '申请取消',
                                    provinceName: provinceName,
                                    areaName: areaName,
                                    manageModelName: manageModelName,
                                    teamName: teamName,
                                    nationName: nationName,
                                    comment: 1,
                                    cancelApply: '否',
                                    leadIndate: moment().format('YYYY-MM-DD')
                                }, { upsert: true });
                            } else {
                                console.log("执行添加")
                                let a2 = await visitMonthPlanModel.create({
                                    sourceId: userId + '&' + element.code,
                                    userId: userId,
                                    user: userName,
                                    avatar: employeeInfo.avatar,
                                    jobnumber: element.employeeName,
                                    deptId: department,
                                    provinceManager: '',
                                    areaManager: '',
                                    modelManager: "",      //模块负责人
                                    nationalManager: "",//全国负责人
                                    city: employeeInfo.workPlace,
                                    roles: employeeInfo.roles,     //角色
                                    province: province,//员工所在省份
                                    area: area,//员工所在区域
                                    manageModel: model,     //员工所在模块
                                    team: team,//员工所在团队
                                    nation: nation,
                                    provinceName: provinceName,//省份名称
                                    areaName: areaName,//区域名称
                                    manageModelName: manageModelName,//模块名称
                                    teamName: teamName,//团队名称
                                    nationName: nationName,//全国名称
                                    month: month,
                                    visitRecoder: '',
                                    channel: '',
                                    mark: '',
                                    planDate: planDate2,
                                    consumerName: element.consumerName,
                                    consumerCode: element.code,
                                    rest: '',
                                    meeting: '',
                                    plantype: type,
                                    planStatus: '申请取消',
                                    customerType:customerType,
                                    purpose: '',
                                    comment: 1,
                                    cancelApply: '否',
                                    remark: '',
                                    leadIndate: moment().format('YYYY-MM-DD')
                                });


                                console.log(a2,'a2_a2_a2_a2_a2_a2_a2_a2_')
                            }
                        }
                    } 
                }
            }
        } 
        console.log('保存导入的计划数据结束!!!!!!!!!!!!!!!!!!11')
    }


}
let visitMonthPlan = new VisitMonthPlanService();
export default visitMonthPlan;